<?php

class Utils {

    /**
     * 参数 转为json格式
     * @url 调用地址
     * @map 设置的参数
     * @return
     */
    public function sendPostGson($url, $map)
    {
        $map_json = stripslashes(json_encode($map));
        return $this->sendPOSTRequest($url, $map_json);
    }

    /**
     * curl 调用接口
     */
    public function sendPOSTRequest($url, $map_json)
    {

        $ch = curl_init();

        //设置选项，包括URL
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // 信任任何证书
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 1); // 检查证书中是否设置域名
		
        //curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE); 
        //curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);

        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $map_json);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array(
            "content-type: application/json; charset=UTF-8"
        ));


        //执行并获取内容
        $content = curl_exec($ch);

        if ($content === false) {
            echo 'Curl error: ' . curl_error($ch);
        }

        //释放curl句柄
        curl_close($ch);

        return $content;

    }

    /**
     * 获取随机字符串
     * @return    随机字符串
     */
    public function createNonceStr()
    {
        // 密码字符集，可任意添加你需要的字符
        $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        $pass = "";
        for ($i = 0; $i < 16; $i++) {
            // 这里提供两种字符获取方式
            // 第一种是使用 substr 截取$chars中的任意一位字符；
            // 第二种是取字符数组 $chars 的任意元素
            $pass .= $chars[mt_rand(0, strlen($chars) - 1)];
        }
        return $pass;
    }

    public function createNonceStr_48()
    {
        // 密码字符集，可任意添加你需要的字符
        $chars = "ace0123456789";
        $pass = "";
        for ($i = 0; $i < 48; $i++) {
            // 这里提供两种字符获取方式
            // 第一种是使用 substr 截取$chars中的任意一位字符；
            // 第二种是取字符数组 $chars 的任意元素
            $pass .= $chars[mt_rand(0, strlen($chars) - 1)];
        }
        return $pass;
    }

    /**
     * 排序
     * @param param    待排序的参数
     * @return    排序结果字符串
     */
    public function sortMap($map)
    {
        ksort($map);
        $data = [];
        foreach ($map as $key => $val) {
            $data[] = $key . '=' . $val;
        }
        return implode('&', $data);
    }

    /**
     * 转换一个String字符串为byte数组
     * @param $str 需要转换的字符串
     * @param $bytes 目标byte数组
     * @author Zikie
     */
    public function getBytes($string)
    {
        $bytes = array();
        for ($i = 0; $i < strlen($string); $i++) {
            $bytes[] = ord($string[$i]);
        }
        return $bytes;
    }

    /**
     *
     *sha256加密
     *
     */
    public function sha256($data, $rawOutput = false)
    {
        if (!is_scalar($data)) {
            return false;
        }
        $data = (string)$data;
        $rawOutput = !!$rawOutput;
        return hash('sha256', $data, $rawOutput);
    }

    /**
     * 签名
     * @param param    待签名的参数
     * @param signKey    签名密钥
     * @return    签名结果字符串
     */
    public function sign($params, $signKey)
    {
        $params_str = $this->sortMap($params);
        $binary_signature = "";
        $algo = "SHA256";
        openssl_sign($params_str, $binary_signature, $signKey, $algo);
        $sign = base64_encode($binary_signature);
        return $sign;

    }

    /**
     * 签名
     * @param symmetricKey 签名秘钥
     * @param params 待加密数据
     * @field    要加密的字段
     */
    public function encryptedParamMap($symmetricKey, $params, $field)
    {
        foreach ($field as $k => $v) {
            $params[$v] = $this->encrypt3DES($params[$v], $symmetricKey);
        }

        return $params;
    }

    /**
     * 加密
     */
    public static function encrypt3DES($data, $key) {
        $key = pack("H48", $key);
        if ($data != ""){
            return base64_encode(openssl_encrypt($data, 'des-ede3', $key, OPENSSL_RAW_DATA));
        }
        return "";
    }

    /**
     * 解密
     */
    public static function decrypt3DES($data, $key) {
        $key = pack("H48", $key);
        if ($data != ""){
            return openssl_decrypt(base64_decode($data), 'des-ede3', $key, OPENSSL_PKCS1_PADDING);
        }
        return "";
    }

    /**
     * 去除\uXXXX (\u0005\u0005)
     */
    public static function unicode_decode($name)
    {
        // 转换编码，将Unicode编码转换成可以浏览的utf-8编码
        $pattern = '/([\w]+)|(\\\u([\w]{4}))/i';
        preg_match_all($pattern, $name, $matches);
        if (!empty($matches))
        {
            $name = '';
            for ($j = 0; $j < count($matches[0]); $j++)
            {
                $str = $matches[0][$j];
                if (strpos($str, '\\u') === 0)
                {
                    $code = base_convert(substr($str, 2, 2), 16, 10);
                    $code2 = base_convert(substr($str, 4), 16, 10);
                    $c = chr($code).chr($code2);
                    $c = iconv('UCS-2', 'UTF-8', $c);
                    $name .= $c;
                }
                else
                {
                    $name .= $str;
                }
            }
        }
        return $name;
    }


    /**
     * 使用公钥加密对称密钥
     * @param publicKey    公钥
     * @param symmetricKeyByte    对称密钥字节
     * @return    加密后的对称密钥字节
     * @throws Exception
     */
    public function encrypt($publicKey, $symmetricKey)
    {

        $key = openssl_pkey_get_public($publicKey);

        if ($key === false) {
            //echo openssl_error_string();EXIT;
            return false;
        }

        $return_en = openssl_public_encrypt($symmetricKey, $crypted, $key);
        if (!$return_en) {
            return false;
        }
        //echo  base64_encode($crypted);exit;
        return base64_encode($crypted);

    }

    //解密
    public function decrypt($privateKey, $symmetricKey)
    {
        //echo $privateKey;
        $key = openssl_pkey_get_private($privateKey);

        if ($key === false) {
            return false;
        }

        $return_en = openssl_private_decrypt(base64_decode($symmetricKey), $decrypted, $key);
        if (!$return_en) {
            echo openssl_error_string();
            EXIT;
            return false;
        }

        return $decrypted;

    }
}


?>